package com.voicechat.firstmet.fragment;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.voicechat.firstmet.MainActivity;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.MyAssignmentsActivity;
import com.voicechat.firstmet.activity.SearchActivity;
import com.voicechat.firstmet.activity.SendPostActivity;
import com.voicechat.firstmet.adapter.AnchorIconAdapter;
import com.voicechat.firstmet.base.BaseFragment;
import com.voicechat.firstmet.bean.CommBean;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.CommunityService;
import com.voicechat.firstmet.utils.AnimationUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.Utils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.fragment
 * @ClassName: CommunityNewFragment
 * @Description: 新版社区页面
 * @Author: ljp
 * @CreateDate: 2019/1/7 10:02
 * @Version: 1.0
 */
public class CommunityNewFragment extends BaseFragment {
    @BindView(R.id.image_search)
    ImageView imageSearch;
    @BindView(R.id.image_im_list)
    ImageView imageImList;
    @BindView(R.id.image_read)
    ImageView imageRead;
    @BindView(R.id.recycler_anchor)
    RecyclerView recyclerAnchor;
    @BindView(R.id.tv_comm_hote)
    TextView tvCommHote;
    @BindView(R.id.tv_comm_new)
    TextView tvCommNew;
    @BindView(R.id.frameLayout)
    FrameLayout frameLayout;
    @BindView(R.id.floatin_button)
    ImageView floatinButton;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    private boolean visible = true;//是否可见，判断是否显示发送帖子按钮
    private int page;//页数，用于初见广场分页加载
    private String token;
    private String deviceInfo;
    Runnable runnable;
    private String userId;
    public static MySelfInfoBean.ObjectBean mySeleInfo;
    private String TAG = "CommunityFragment";
    //热门信息数据list
    private ArrayList<CommBean.MapBean.RealTimeBean> commBeans = new ArrayList<>();
    private String showFragmentTag;
    private CommunityHotPostFragment communityHotPostFragment;
    private CommunityNewPostFragment communityNewPostFragment;
    private AnchorIconAdapter anchorIconAdapter;
    private Fragment currentFragment;

    public static CommunityNewFragment newInstance() {
        CommunityNewFragment fragment = new CommunityNewFragment();
        return fragment;
    }

    @Override
    protected int loadLayout() {
        return R.layout.fragment_new_community;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this, view);
        page = 1;
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        userId = mySeleInfo.getId();
        initView();
        clearSelection();
        tvCommHote.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        replaceFragment("0");
    }

    /**
     * @return
     * @method
     * @description 数据控件实例化
     * @date: 2019/1/8 15:24
     * @author: ljp
     */
    private void initView() {
        smartRefresh.autoRefresh();
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                Intent intent = new Intent("post");
                httpHotInfo();
                intent.putExtra("change", "Refresh");
                LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
                smartRefresh.finishRefresh(10000);
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                Intent intent = new Intent("post");
                intent.putExtra("change", "LoadMore");
                LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
                smartRefresh.finishLoadMore(10000);
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        AnimationUtils.showFABAnimation(floatinButton);
        anchorIconAdapter = new AnchorIconAdapter(context, commBeans, R.layout.item_picure);
        recyclerAnchor.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        recyclerAnchor.setAdapter(anchorIconAdapter);
    }

    private void replaceFragment(String tag) {
        showFragmentTag = tag;
        if (currentFragment != null) {
            getChildFragmentManager().beginTransaction().detach(currentFragment).commit();
        }
        currentFragment = getChildFragmentManager().findFragmentByTag(tag);
        if (currentFragment == null) {
            switch (tag) {
                case "0":
                    currentFragment = new CommunityHotPostFragment();
                    break;
                case "1":
                    currentFragment = new CommunityNewPostFragment();
                    break;
            }
            getChildFragmentManager().beginTransaction().add(R.id.frameLayout, currentFragment, tag).commit();
        } else {
            getChildFragmentManager().beginTransaction().attach(currentFragment).commit();
        }
    }

    //刷新
    public void setSmartRefresh() {
        smartRefresh.finishRefresh();
    }

    //没有更多了
    public void setSmartLoad(String flag) {
        if (flag.equals("more")) {
            smartRefresh.finishLoadMore();//下来加载更多
        } else {
            smartRefresh.finishLoadMoreWithNoMoreData();//没有更多了
        }
    }

    /**
     * @return
     * @method
     * @description 请求热门信息（banner、实时推荐、广告位、热门帖子）
     * @date: 2018/10/9 13:52
     * @author: ljp
     */
    private void httpHotInfo() {
        CommunityService.communityHotInfo(token, deviceInfo, userId).subscribe(coummunityNotice -> {
           // Log.i(TAG, "httpHotInfo: -----------" + coummunityNotice.getMap().getRealTime().size());
            if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                commBeans.clear();
                commBeans.addAll(coummunityNotice.getMap().getRealTime());
                anchorIconAdapter.notifyDataSetChanged();
                //smartRefresh.finishRefresh();
            } else if (coummunityNotice.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(coummunityNotice.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "httpHotInfo: -------" + throwable.toString());
        });
    }

    @OnClick({R.id.image_search, R.id.tv_comm_hote, R.id.tv_comm_new, R.id.floatin_button
    ,R.id.linear_voice_chate, R.id.linear_share_girls, R.id.linear_share_photo, R.id.linear_sign_in})
    public void onClick(View view) {
        switch (view.getId()) {
            //搜索按钮
            case R.id.image_search:
                startActivity(new Intent(activity, SearchActivity.class));
                break;
            //切换热门
            case R.id.tv_comm_hote:
                clearSelection();
                tvCommHote.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                replaceFragment("0");
                break;
            //切换最新
            case R.id.tv_comm_new:
                clearSelection();
                tvCommNew.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                replaceFragment("1");
                break;
            //发布帖子按钮
            case R.id.floatin_button:
                startActivity(new Intent(context, SendPostActivity.class));
                break;
            case R.id.linear_voice_chate://语聊
                ((MainActivity) getActivity()).setFrame(1);
                break;
            case R.id.linear_share_girls://共享闺蜜
                ((MainActivity) getActivity()).setFrame(10);
                break;
            case R.id.linear_share_photo://共享秀照
                ((MainActivity) getActivity()).setFrame(20);
                break;
            case R.id.linear_sign_in://签到
                startActivity(new Intent(activity, MyAssignmentsActivity.class));
                break;
        }
    }
    @Override
    protected void clearSelection() {//清空底部Tab的选中状态,当点击的时候再自定义选中Tab的状态
        super.clearSelection();
        tvCommHote.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        tvCommNew.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
    }


}
